package com.xy.smartsms.util;

import android.os.Looper;
import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by admin on 2017/3/3.
 */

public class CommonUtils {
    static public String getCacheKey(String msgId, long receiveTime) {
        return msgId + receiveTime + "";
    }

    public static boolean isMainThread() {
        return (Looper.myLooper() == Looper.getMainLooper()) ? true : false;
    }

    /**
     * format PhoneNumber before parse message
     */
    public static String formatPhoneNum(String phoneNumber) {
        if (TextUtils.isEmpty(phoneNumber)) {
            return null;
        }

        phoneNumber = phoneNumber.replace(" ", "").replace("-", "").replace("(", "").replace(")", "");
        if (phoneNumber.startsWith("+86")) {
            phoneNumber = phoneNumber.replaceFirst("\\+86", "");
        } else if (phoneNumber.startsWith("0086")) {
            phoneNumber = phoneNumber.replaceFirst("0086", "");
        } else if (phoneNumber.startsWith("86")) {
            phoneNumber = phoneNumber.replaceFirst("86", "");
        } else if (phoneNumber.startsWith("17951") && phoneNumber.length() > 10) {
            phoneNumber = phoneNumber.replaceFirst("17951", "");
        } else if (phoneNumber.startsWith("12593") && phoneNumber.length() > 10) {
            phoneNumber = phoneNumber.replaceFirst("12593", "");
        } else if (phoneNumber.startsWith("12520") && phoneNumber.length() > 10) {
            phoneNumber = phoneNumber.replaceFirst("12520", "");
        }

        return phoneNumber;
    }

    public static String hashKey(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }

        return cacheKey;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }

        return sb.toString();
    }


}
